package detect;

import interfaces.Detect;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;

import entities.Domain;
import entities.JsTechnology;

public class DetectJsJqueryColorbox implements Detect {
	@SuppressWarnings("serial")
	@Override
	public void getInfo(Map<String, Object> obj) {
		// TODO Auto-generated method stub
		Document doc = (Document) obj.get("doc");
		Domain domain = (Domain) obj.get("domain");

		Type listType = new TypeToken<List<JsTechnology>>() {
		}.getType();
		List<JsTechnology> jsTechnologies = new Gson().fromJson(
				domain.getJsTechnology(), listType);

		if (jsTechnologies == null) {
			jsTechnologies = new ArrayList<JsTechnology>();
		}

		try {
			JsTechnology jsTechnology = new JsTechnology();
			Elements listJs = doc.select("script");
			String jsName = "";
			String jsVersion = "";
			for (Element js : listJs) {
				String src = js.attr("src");
				if (!src.isEmpty()
						&& src.toLowerCase().contains("jquery.colorbox")) {
					jsName = "jQuery";
					String name = src.replaceAll("[^/]*[/]+", "").replaceAll(
							"[?]+[^?]*", "");

					Pattern p = Pattern.compile("([0-9]+[.]{1})+[0-9]{1}");
					Matcher m = p.matcher(name); // get a matcher object
					while (m.find()) {
						jsVersion = name.substring(m.start(), m.end());
						break;
					}

					if (jsVersion.isEmpty()) {
						m = p.matcher(src); // get a matcher object
						while (m.find()) {
							jsVersion = src.substring(m.start(), m.end());
							break;
						}
					}
				}
			}

			if (!jsName.isEmpty()) {
				jsTechnology.setN(jsName);
				jsTechnology.setV(jsVersion);

				jsTechnologies.add(jsTechnology);
			}

			domain.setJsTechnology(new Gson().toJson(jsTechnologies));
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
